<template>
  <div class="addCamera">
    <el-button v-if="showBtn" @click="handleClick" v-bind="$attrs">
      <slot>新增</slot>
    </el-button>
    <el-dialog class="d1" :title="title" :visible.sync="visible" append-to-body width="500px" @close="onClose">
      <el-form :model="form" ref="form" v-loading="loading" class="form rules" :rules="rules" label-width="140px" size="mini">
        <el-form-item label="供应商名称：" prop="supplierName">
          <el-input v-model.trim="form.supplierName" maxlength="30" size="small" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="供应商负责人：" prop="supplierRepo">
          <el-input v-model.trim="form.supplierRepo" maxlength="20" size="small" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="供应商联系方式：" prop="supplierPhone">
          <el-input v-model.trim="form.supplierPhone" maxlength="11" size="small" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="供应商地址：" prop="illusory">
          <areaSelector v-model.trim="form.illusoryResult" :value="areaValue" size="small" style="width:100%" placeholder="请输入" @change="handleAreachange"></areaSelector>
        </el-form-item>
        <el-form-item label="详细地址：" prop="supplierDetailedAddress">
          <el-input v-model.trim="form.supplierDetailedAddress" maxlength="255" size="small" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="供应商网址：" prop="supplierUrl">
          <el-input v-model.trim="form.supplierUrl" maxlength="50" size="small" placeholder="请输入"></el-input>
        </el-form-item>
        <div class="align-r">
          <el-button size="small" @click="visible=false">取 消</el-button>
          <el-button size="small" type="primary" @click="handleSubmit">确 定</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
  import areaSelector from "../../../components/areaSelector";
  import { addSupplier, updateSupplier, checkSupplierName } from '@/api/slope/supplier';
  export default {
    components: {
      areaSelector
    },
    props: {
      showBtn: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        loading: false,
        visible: false,
        changeSupplierNameValue: null, // 是修改状态时修改imei之前的值
        title: "",
        areaValue:[],
        defaultForm: {
          supplierName:"",
          supplierRepo:"",
          supplierPhone:"",
          illusoryResult:[],
          supplierDetailedAddress:"",
          supplierRoughlyAddress:"北京市 市辖区 西城区 110000 110100 110102",
          supplierUrl:"",
          isValid:"0"
        },
        form: {
          supplierName:"",
          supplierRepo:"",
          supplierPhone:"",
          illusoryResult:[],
          supplierRoughlyAddress:"",
          supplierDetailedAddress:"",
          supplierUrl:"",
          isValid:"0"
        },
        rules: {
          supplierName: [{
            required: true,
            message: "供应商名称不能为空"
          },{
            validator: (rule, value, callback) => {
              if (this.changeSupplierNameValue != value) {
                checkSupplierName(value).then(res => {
                  if (res.data.length > 0) {
                    callback('供应商名称不能重复');
                  } else {
                    callback()
                  }
                })
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }],
          supplierRepo: {required: true,message: "负责人姓名不能为空"},
          supplierPhone: {required: true,message: "供应商联系方式不能为空"},
          supplierRoughlyAddress: {required: true,message: "供应商地址不能为空"},
          supplierDetailedAddress: {required: true,message: "供应商详细地址不能为空"},
        }
      };
    },
    methods: {
      onClose() {
        this.form = {
          ...this.defaultForm
        };
      },
      handleAreachange(result) {
        let self = this;
        try {
          self.form.supplierRoughlyAddress = result.join(" ") +" "+self.form.illusoryResult.join(" ");
        }catch (error) {
          self.form.supplierRoughlyAddress="北京市 市辖区 西城区 110000 110100 110102"
        }
      },
      async handleClick({ info, title, submit }) {
        let self = this;
        self.form = {
          ...self.defaultForm,
          ...info
        } || {
           ...self.defaultForm
        };

        if(self.form.supplierId != undefined){
          console.log(info.supplierName);
          self.changeSupplierNameValue = info.supplierName; // 修改时给原先的IMEI赋值
        }

        try {
            let test = self.form.supplierRoughlyAddress.split(" ");
            let illusoryResult = [];
            for (let i = 3; i < test.length; i++) {
              illusoryResult.push(test[i]);
            }
            self.form.illusoryResult = illusoryResult;
            self.areaValue = illusoryResult;
        } catch (error) {

        }
        self.title = title || "";
        self.submit = submit || (() => {});
        self.visible = true;
        await self.$nextTick();
        self.$refs["form"].clearValidate();
      },
      async handleSubmit(data) {
        let self = this;
        self.$refs["form"].validate(async valid => {
          if (valid) {
            let result = '';
            self.loading = true;
            if (self.form.supplierId != undefined) {
              updateSupplier(self.form).then(response => {
                if (response.code === 200) {
                  self.msgSuccess("修改成功");
                  self.visible = false;
                  self.$parent.getList();
                } else {
                  self.msgError(response.msg);
                }
                self.loading = false;
              }).catch((error)=> {
                self.loading = false;
                console.log(error);
              });
            } else {
              addSupplier(self.form).then(response => {
                if (response.code === 200) {
                  self.msgSuccess("新增成功");
                  self.visible = false;
                  self.$parent.getList();
                } else {
                  self.msgError(response.msg);
                }
                self.loading = false;
              }).catch((error)=> {
                self.loading = false;
                console.log(error);
              });
            }
          }
        });
      },
      // 表单重置
      reset() {
        if (this.$refs.tree != undefined) {
          this.$refs.tree.setCheckedKeys([]);
        }
        this.form = {
          roleId: undefined,
          roleName: undefined,
          roleKey: undefined,
          roleSort: 0,
          status: "0",
          menuIds: [],
          deptIds: [],
          remark: undefined
        };
        this.resetForm("form");
      },
    }
  };
</script>
